package com.shuai.chatroom.common;

import com.shuai.chatroom.exception.ControllerException;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class PhotoUtils {
    public static String uploadPhoto(@RequestPart("uploadPhoto") MultipartFile multipartFile, String rootPath) throws ControllerException, IOException {
        if (multipartFile.isEmpty()) {
            throw new ControllerException("参数缺失！");
        }
        String originalFilename = multipartFile.getOriginalFilename();//上传的文件的名称
        String suffix = null;  //上传文件的格式
        suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!".png".equals(suffix)
                && !".jpg".equals(suffix)
                && !".jpeg".equals(suffix)) {
            throw new ControllerException("头像格式错误！");
        }
        //将文件保存到本地
        String finalFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        multipartFile.transferTo(new File(rootPath + finalFileName));
        return finalFileName;   //返回生成的最终文件名＋后缀
    }
}
